<?php

namespace app\api\controller;

use addons\qiniu\library\Auth;
use app\admin\model\finance\extract\Week;
use app\admin\model\halt\Cate;
use app\admin\model\Preproduct;
use app\common\controller\Yangliu;
use app\admin\model\School;
use app\common\model\Attachment;
use think\Config;


/**
 *  杨柳 公共接口
 */
class CommonApi extends Yangliu
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
    protected $model;
    protected $school;
    protected $week;
    protected $preproduct;
    protected $jurisdiction;

    public function _initialize()
    {
        parent::_initialize();
        $this->week = new Week();//周数据
        $this->school = new School();//学校数据
        $this->preproduct = new Preproduct();//产品
        $this->jurisdiction = $this->auth->Auth();
    }

    /**
     * @ApiTitle    (学校查询)
     * @ApiSummary  (学校查询)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/common_api/school)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="page", type="integer", required=false, description="第几页,默认第一页")
     * @ApiParams   (name="limit", type="string", required=false, description="每页条数,默认10条")
     * @ApiParams   (name="where[name]", type="array", required=false, description="学校名称")
     * @ApiParams   (name="where[province]", type="array", required=false, description="省")
     * @ApiParams   (name="where[city]", type="array", required=false, description="市")
     * @ApiParams   (name="where[area]", type="array", required=false, description="区县")
     * @ApiParams   (name="where[type]", type="array", required=false, description="类别")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="total", type="integer", required=true, description="总条数")
     * @ApiReturnParams   (name="per_page", type="integer", required=true, description="每页数")
     * @ApiReturnParams   (name="current_page", type="integer", required=true, description="当前页")
     * @ApiReturnParams   (name="last_page", type="integer", required=true, description="最后一页")
     * @ApiReturnParams   (name="id", type="integer", required=true, description="主键ID")
     * @ApiReturnParams   (name="name", type="string", required=true, description="name")
     * @ApiReturnParams   (name="province", type="string", required=true, description="1")
     * @ApiReturnParams   (name="city", type="string", required=true, description="2")
     * @ApiReturnParams   (name="area", type="string", required=true, description="4")
     * @ApiReturnParams   (name="type", type="string", required=true, description="3")
     * @ApiReturn   ({
    code: 1,
    msg: "",
    time: "1575096350",
    data: {
    total: 1,
    per_page: 10,
    current_page: 1,
    last_page: 1,
    data: [
    {
    id: 1,
    name: "北京市第四中学",
    province: 1,
    city: 2,
    area: 4,
    address: "西黄城根北街甲2号",
    category: "A",
    type: "3",
    class: 0,
    total_number: 0,
    textbook_edition: "",
    policylist: null,
    is_schoolsdata: "1",
    total_score: "",
    volume: null,
    teaching_order: null,
    bookstore: "",
    createtime: 1542265427,
    updatetime: 1542265427,
    category_text: "A",
    type_text: "高中",
    policylist_text: "",
    is_schoolsdata_text: "Is_schoolsdata 1",
    volume_text: "",
    teaching_order_text: "",
    province_text: "北京",
    city_text: "北京市",
    area_text: "西城区"
    }
    ]
    }
    })
     */
    public function school()
    {
        list($where, $order, $limit) = $this->buildparams(false);
        $list = $this->school
            ->where($where)
            ->order($order)
            ->paginate($this->request->request('Pagesize',$limit),false);
        $this->success('',$list);
    }

    /**
     * @ApiTitle    (学校详情)
     * @ApiSummary  (学校详情)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/common_api/schoolShow/id/{id})
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="id", type="integer", required=true, description="学校id")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="science_class", type="integer", required=true, description="文科班数量")
     * @ApiReturnParams   (name="arts_class", type="integer", required=true, description="理科班数量")
     * @ApiReturnParams   (name="science_num", type="integer", required=true, description="文科生数量")
     * @ApiReturnParams   (name="arts_num", type="integer", required=true, description="理科生数量")
     * @ApiReturnParams   (name="up_year", type="integer", required=true, description="上学年本校是否 1 是 2否")
     * @ApiReturnParams   (name="sales_volume", type="string", required=true, description="上学年销量")
     * @ApiReturnParams   (name="class", type="integer", required=true, description="总班级数")
     * @ApiReturnParams   (name="total_number", type="integer", required=true, description="总人数")
     * @ApiReturn   ({
    "code": 1,
    "msg": "学校详细信息",
    "time": "1575599648",
    "data": {
    "id": 1,
    "name": "北京市第四中学",
    "province": 1,
    "city": 2,
    "area": 4,
    "address": "西黄城根北街甲2号",
    "category": "A",
    "type": "3",
    "class": 0,
    "total_number": 0,
    "textbook_edition": "",
    "policylist": null,
    "is_schoolsdata": "1",
    "total_score": "",
    "volume": null,
    "teaching_order": null,
    "bookstore": "",
    "createtime": 1542265427,
    "updatetime": 1542265427,
    "science_num": null,
    "arts_num": null,
    "science_class": null,
    "arts_class": null,
    "up_year": 1,
    "sales_volume": null,
    "category_text": "A",
    "type_text": "高中",
    "policylist_text": "",
    "is_schoolsdata_text": "Is_schoolsdata 1",
    "volume_text": "",
    "teaching_order_text": "",
    "province_text": "北京",
    "city_text": "北京市",
    "area_text": "西城区"
    }
    })
     */
    public function schoolShow($id = null)
    {
        $row = $this->school->get($id);
        $this->success('学校详细信息',$row);
    }

    /**
     * @ApiTitle    (更新学校数据 )
     * @ApiSummary  (更新学校数据 )
     * @ApiMethod   (POSt)
     * @ApiRoute    (/api/common_api/schoolEdit)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="update[id]", type="integer", required=true, description="学校ID")
     * @ApiParams   (name="update[science_class]", type="string", required=true, description="文科班数量")
     * @ApiParams   (name="update[arts_class]", type="string", required=true, description="理科班数量")
     * @ApiParams   (name="update[science_num]", type="string", required=true, description="文科生数量")
     * @ApiParams   (name="update[arts_num]", type="string", required=true, description="理科生数量")
     * @ApiParams   (name="update[sales_volume]", type="string", required=true, description="上学年销量")
     * @ApiParams   (name="update[up_year]", type="string", required=true, description="上学年本校是否 1 是 2否")
     * @ApiParams   (name="update[class]", type="string", required=true, description="总班级数")
     * @ApiParams   (name="update[total_number]", type="string", required=true, description="总人数")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "更新完成",
    "time": "1575599770",
    "data": null
    })
     */
    public function schoolEdit()
    {
        if(!$data = $this->request->request('update/a'))
        {
            $this->error('请提交有效的数据');
        }
        $this->school->update($data);
        $this->success('更新完成');
    }

    /**
     * @ApiTitle    (产品信息 )
     * @ApiSummary  (信息 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/common_api/getproduct)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="where[classif]", type="integer", required=true, description="分类id")
     * @ApiParams   (name="where[cname]", type="string", required=true, description="搜索商品名称")
     * @ApiParams   (name="page", type="integer", required=false, description="第几页,默认第一页")
     * @ApiParams   (name="limit", type="string", required=false, description="每页条数,默认10条")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturnParams   (name="total", type="integer", required=true, description="总条数")
     * @ApiReturnParams   (name="per_page", type="integer", required=true, description="每页数")
     * @ApiReturnParams   (name="current_page", type="integer", required=true, description="当前页")
     * @ApiReturnParams   (name="last_page", type="integer", required=true, description="最后一页")
     * @ApiReturn  ({
    "code": 1,
    "msg": "",
    "time": "1575447814",
    "data": {
    "total": 166,
    "per_page": 15,
    "current_page": 1,
    "last_page": 12,
    "data": [
    {
    "id": 171,
    "cname": "小学生绘本课堂 数学 六年级 北师版B2",
    "classif": 29,
    "storenum": 0,
    "storecall": 1,
    "uname": "admin",
    "ctime": 1568942137,
    "remark": "",
    "class_text": "1,2,29",
    "b_n": "5d8428395b3e8",
    "bcp": "",
    "type": "1",
    "price": "0.00",
    "image": "",
    "cnames": null,
    "classif_text": "",
    "ctime_text": "2019-09-20 09:15:37"
    }
    ]
    }
    })
     */
    public function getProduct()
    {
        list($where, $order, $limit) = $this->buildparams(false);
        $where['stylebook']=1;
        $list = $this->preproduct
            ->where($where)
            ->order($order)
            ->paginate($this->request->request('Pagesize',$limit),false);

        $this->success('',$list);
    }

    /**
     * @ApiTitle    (产品分类)
     * @ApiSummary  (产品分类 )
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/common_api/cate)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn  ({
    "code": 1,
    "msg": "",
    "time": "1575447760",
    "data": [
    {
    "id": 17,
    "pid": 2,
    "name": "学习书",
    "createtime": 1568861584,
    "updatetime": 1568861584,
    "type": "1",
    "product": "35",
    "kemu": "",
    "banben": ""
    },
    {
    "id": 29,
    "pid": 2,
    "name": "数学",
    "createtime": 1568941726,
    "updatetime": 1568941726,
    "type": "1",
    "product": "35",
    "kemu": "",
    "banben": ""
    }
    ]
    })
     */
    public function Cate()
    {
        $cateDb = new Cate();
        $cate = collection($cateDb->where(array("pid" => 2))->select())->toArray();
        $this->success('',$cate);
    }

    /**
     * @ApiTitle    (七牛云上传文件)
     * @ApiSummary  (七牛云上传文件)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/common_api/upload)
     * @ApiParams   (name="file", type="file", required=true, description="文件")
     * @ApiParams   (name="token", type="string", required=true, description="token")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn   ({
    "code": 1,
    "msg": "上传成功",
    "time": "1575373106",
    "data": {
    "url": "/uploads/20191203/9c1a8d0f67225f4ec487fed3c67253d1.png"
    }
    })
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        if (!$this->auth->id) {
            $this->error("请登录后再进行操作");
        }
        $config = get_addon_config('qiniu');

        $file = $this->request->file('file');
        if (!$file || !$file->isValid()) {
            $this->error("请上传有效的文件");
        }
        $fileInfo = $file->getInfo();

        $filePath = $file->getRealPath() ?: $file->getPathname();

        preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$config['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);

        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $md5 = md5_file($filePath);
        $search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
        $replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
        $object = ltrim(str_replace($search, $replace, $config['savekey']), '/');

        $mimetypeArr = explode(',', strtolower($config['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //检查文件大小
        if (!$file->checkSize($size)) {
            $this->error("起过最大可上传文件限制");
        }

        //验证文件后缀
        if ($config['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $config['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            $this->error(__('上传格式限制'));
        }

        $savekey = '/' . $object;

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);
        //先上传到本地
        $splInfo = $file->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $extparam = $this->request->post();
            $filePath = $splInfo->getRealPath() ?: $splInfo->getPathname();

            $sha1 = sha1_file($filePath);
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $params = array(
                'username'    => $this->auth->username,
                'userid'     => $this->auth->userid,
                'filesize'    => $fileInfo['size'],
                'imagewidth'  => $imagewidth,
                'imageheight' => $imageheight,
                'imagetype'   => $suffix,
                'imageframes' => 0,
                'mimetype'    => $fileInfo['type'],
                'url'         => $uploadDir . $splInfo->getSaveName(),
                'uploadtime'  => time(),
                'storage'     => 'local',
                'sha1'        => $sha1,
                'extparam'    => json_encode($extparam),
            );
            $attachment = Attachment::create(array_filter($params), true);
            $policy = array(
                'saveKey' => ltrim($savekey, '/'),
            );
            $auth = new Auth($config['app_key'], $config['secret_key']);
            $token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
            $multipart = [
                ['name' => 'token', 'contents' => $token],
                [
                    'name'     => 'file',
                    'contents' => fopen($filePath, 'r'),
                    'filename' => $fileName,
                ]
            ];
            try {
                $client = new \GuzzleHttp\Client();
                $res = $client->request('POST', $config['uploadurl'], [
                    'multipart' => $multipart
                ]);
                $code = $res->getStatusCode();
                //成功不做任何操作
            } catch (\GuzzleHttp\Exception\ClientException $e) {
                $attachment->delete();
                unlink($filePath);
                $this->error("上传失败");
            }

            $url = '/' . $object;

            //上传成功后将存储变更为qiniu
            $attachment->storage = 'qiniu';
            $attachment->save();

            $this->success("上传成功", null, ['url' => 'http://oaimg.fc62.com'.$url]);
        } else {
            $this->error('上传失败');
        }
        return;
    }
    
    /**
     * @ApiTitle    (获取周数据)
     * @ApiSummary  (获取周数据)
     * @ApiMethod   (POSt)
     * @ApiRoute    (/api/common_api/getweek)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="status", type="string", required=false, description="状态")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn   ({
    "code": 1,
    "msg": "",
    "time": "1574999118",
    "data": [
    {
    "id": 2,
    "value": 2018,
    "childs": [
    {
    "id": 2,
    "value": "第33周,08.20-08.26周数据"
    }
    ]
    }
    ]
    })
     */
    public function getWeek()
    {
        $where = '';
        //字符串拼接
        if(!$this->auth->Auth() == 'all')
        {
            //获取当前部门
            $where = [
                'department'=>['in',explode(',',$this->auth->department)]
            ];
        }
        $list = $this->week
            ->where($where)
            ->group('year')
            ->select();
        if($status = $this->request->request('status'))
        {
            $where = 'status = 2 OR status = -2';
        }
        $year = [];
        foreach ($list as $value)
        {
            $year[] = [
                'id'=>$value['id'],
                'value'=>$value['year'],
                'childs'=>$this->weeklyData($where)
            ];
        }
        $this->success('',$year);
    }

    /**
     * @ApiTitle    (获取定位的详细地址)
     * @ApiSummary  (获取定位的详细地址)
     * @ApiMethod   (Get)
     * @ApiRoute    (/api/common_api/getAddress)
     * @ApiParams   (name="token", type="string", required=true, description="用户token")
     * @ApiParams   (name="location", type="string", required=true, description="经度,纬度 (1312,2121))
     * @ApiReturnParams   (name="code", type="integer", required=true, description="0成功。其他都失败")
     * @ApiReturnParams   (name="msg", type="string", required=true, description="返回成功")
     * @ApiReturnParams   (name="time", type="integer", required=true, description="时间戳")
     * @ApiReturn   ()
     */
    public function getAddress()
    {
        $location = $this->request->request('location');
        $url = "https://apis.map.qq.com/ws/geocoder/v1/?location={$location}&key=HB5BZ-XKS34-G56UJ-DPLCQ-SK6DS-POBNO&get_poi=0&output=json";
        $address = \fast\Http::get($url);
        $this->success('',json_decode($address,true));
    }

    protected function weeklyData($where)
    {
        $list = $this->week
            ->where($where)
            ->select();
        $arr = [];
        foreach ($list as $value)
        {
            $arr[] = [
                'id'=>$value['id'],
                'value'=>'第'.$value['week_text'].'周,'.$value['name']
            ];
        }
        return $arr;
    }
}
